<template>
  <div>
    <el-form ref="myform1" :model="formItem" :rules="rules" label-width="100px" size="mini">
      <el-row>
        <el-col :span="12">
          <el-form-item label="工单标题" prop="title">
            <el-input v-model="formItem.title" placeholder="请输入标题" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="到货日期" prop="receiveDate">
            <el-date-picker v-model="formItem.receiveDate" type="date" placeholder="请选择到货日期" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="存放位置" prop="location">
            <treeselect
              v-model="formItem.location"
              :multiple="false"
              :options="myStorehouses"
              :disable-branch-nodes="true"
              placeholder="请选择存放位置"
              @input="inputLocation"
              @select="selectLocation"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入库类型" prop="categories">
            <el-radio-group v-model="formItem.categories" size="mini" @change="categorieChange">
              <el-radio label="1" value="1">非消耗品</el-radio>
              <!-- <el-radio label="2" value="2" border>低值易耗品</el-radio> -->
              <el-radio label="3" value="3">消耗品</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="综合管理部" prop="comprehensive">
            <el-radio-group v-model="formItem.comprehensive">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col> -->
        <el-col :span="24">
          <el-form-item label="备注信息" prop="remark">
            <el-input v-model="formItem.remark" type="textarea" placeholder="请输入备注信息" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="资产明细">
            <el-button size="mini" type="primary" icon="el-icon-plus" style="margin-bottom: 15px;" @click="assetDialogFormVisible = true">添加资产</el-button>
            <PageableTable
              :columns="insideColumns"
              :loading="false"
              :table-height="240"
              :data="formItem.assetList"
              :disable-pageable="true"
              border
              class="fixed-table-table"
            >
              <el-table-column
                label="序号"
                type="index"
                width="50"
                header-align="center"
                align="center"
              />
              <el-table-column v-for="column in insideColumns" :key="column.key" header-align="center" align="center" :label="column.title" :prop="column.key" :sortable="column.sortable">
                <template slot-scope="scope">
                  <column-render :render="column.render" :row="scope.row" :column="column" />
                </template>
              </el-table-column>
              <el-table-column label="操作" header-align="center" align="center" width="150" class-name="small-padding fixed-width" fixed="right">
                <template slot-scope="scope">
                  <el-button type="text" size="mini" icon="el-icon-edit-outline" title="编辑" @click="editRow(scope)">编辑</el-button>
                  <el-button type="text" size="mini" icon="el-icon-delete" title="移除" @click="remove(scope.row)">移除</el-button>
                </template>
              </el-table-column>
            </PageableTable>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="配件明细">
            <el-button size="mini" type="primary" icon="el-icon-plus" style="margin-bottom: 15px;" @click="goodsFileDialogFormVisible = true">添加配件</el-button>
            <PageableTable
              :columns="goodsFileInsideColumns"
              :loading="false"
              :table-height="240"
              :data="formItem.goodsFileList"
              :disable-pageable="true"
              border
              class="fixed-table-table"
            >
              <el-table-column
                label="序号"
                type="index"
                width="50"
                header-align="center"
                align="center"
              />
              <el-table-column v-for="column in goodsFileInsideColumns" :key="column.key" header-align="center" align="center" :label="column.title" :prop="column.key" :sortable="column.sortable">
                <template slot-scope="scope">
                  <column-render :render="column.render" :row="scope.row" :column="column" />
                </template>
              </el-table-column>
              <el-table-column label="操作" header-align="center" align="center" width="150" class-name="small-padding fixed-width" fixed="right">
                <template slot-scope="scope">
                  <el-button type="text" size="mini" icon="el-icon-edit-outline" title="编辑" @click="editGoodsFileRow(scope)">编辑</el-button>
                  <el-button type="text" size="mini" icon="el-icon-delete" title="删除" @click="removeGoodsFile(scope.row)">移除</el-button>
                </template>
              </el-table-column>
            </PageableTable>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="">
            <el-button size="mini" @click="btnCancel">取 消</el-button>
            <el-button size="mini" type="warning" @click="commit(true)">暂 存</el-button>
            <el-button size="mini" type="primary" @click="commit(false)">提 交</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <FormDialog
      v-if="assetDialogFormVisible"
      title="新建"
      :append-to-body="true"
      :show="assetDialogFormVisible"
      width="80%"
      @on-ok="ok"
      @on-cancel="cancel"
    >
      <EditForm v-if="assetDialogFormVisible" :id="editId" ref="editForm" :categories="formItem.categories" belongs="kj" />
    </FormDialog>

    <FormDialog
      v-if="goodsFileDialogFormVisible"
      title="新建"
      :append-to-body="true"
      :show="goodsFileDialogFormVisible"
      width="60%"
      @on-ok="goodsFileOk"
      @on-cancel="goodsFileCancel"
    >
      <GoodsFile v-if="goodsFileDialogFormVisible" :id="goodsEditId" ref="goodsEditForm" />
    </FormDialog>
  </div>
</template>
<script>
import treeselect from '@neu/biz-core/components/TreeSelect'
import { create, detail } from '@neu/dcam-ui/api/rukuKJ'
import { formatDate } from '@neu/biz-core/utils/utils'
import { tree as locationTree } from '@neu/dcam-ui/api/location'
import { list as getAllStorehouse } from '@neu/dcam-ui/api/storehouse'
import PageableTable from '@neu/biz-core/components/PageableTable'
import EditForm from './asset'
import GoodsFile from './goodsFile'
import FormDialog from '@neu/biz-core/components/FormDialog'
import { clone } from '@neu/biz-core/utils/utils'

const formItem = {
  /** 工单号 */
  workOrderNum: '',
  /** 任务ID */
  taskId: '',
  /** 标题 */
  title: '',
  /** 到货日期 */
  receiveDate: null,
  /** 备注 */
  remark: '',
  /** 是否为暂存 */
  temporary: true,
  // 是否为自动工单
  autogenerate: false,
  /** 购置日期 */
  //   purchaseDate: null,
  /** 是否为综合管理部 */
  comprehensive: true,
  /** 存放位置编码 */
  location: null,
  /** 存放位置编码 */
  locationName: '',
  /** 资产分类 */
  categories: '1',
  /** 资产详情 */
  assetList: [],
  /** 配件详情 */
  goodsFileList: []
}
export default {
  components: {
    treeselect,
    FormDialog,
    EditForm,
    GoodsFile,
    PageableTable
  },
  props: {
    taskId: {
      required: false,
      type: String,
      default: 'NULL'
    },
    workOrderNum: {
      required: false,
      type: String,
      default: ''
    },
    orderStatus: {
      required: false,
      type: String,
      default: 'NULL'
    }
  },
  data() {
    return {
      formItem: { ...formItem },
      /** 资产弹窗 */
      assetDialogFormVisible: false,
      /** 配件弹窗 */
      goodsFileDialogFormVisible: false,
      /** 仓库 */
      availableLocations: [],
      /** 扁平化长裤 */
      flattenTreeData: [],
      /** 表格列 */
      insideColumns: [],
      goodsFileInsideColumns: [
        { title: '配件名称', key: 'name' },
        { title: '配件分类', key: 'spareTypeName' },
        { title: '规格型号', key: 'specification' },
        { title: '配件描述', key: 'description' }
      ],
      /** 表格列原始数据 */
      sInsideColumns: [
        { title: '原始编号', width: 100, key: 'originalCode', display: true },
        { title: '资产名称', width: 140, key: 'name', display: true },
        // { title: '资产编号', width: 140, key: 'code', display: true },
        { title: '资产分类', width: 200, key: 'type',
          render: (h, params) => {
            let txt = params.row.smallTypeName
            if (params.row.middleTypeName) {
              txt = params.row.middleTypeName + ' / ' + txt
            }
            if (params.row.bigTypeName) {
              txt = params.row.bigTypeName + ' / ' + txt
            }
            return h('span', txt)
          }
        },
        { title: '购置日期', width: 100, key: 'purchaseDate', render: (h, params) => { return h('span', formatDate(params.row.purchaseDate, 'YYYY-MM-DD')) }, display: true },
        { title: '供应商', width: 100, key: 'supplierName', display: true },
        { title: '品牌', width: 100, key: 'brand', display: true },
        { title: '规格型号', width: 100, key: 'specifications', display: true },
        { title: '序列号', width: 100, key: 'serialnumber', display: true },
        // { title: '机房', width: 100, key: 'computerRoom', display: true },
        // { title: '机柜', width: 100, key: 'cabinet', display: true },
        { title: '位置', width: 100, key: 'locationName', display: true },
        { title: '维保开始', width: 150, key: 'maintenanceStartTime', render: (h, params) => { return h('span', formatDate(params.row.maintenanceStartTime, 'YYYY-MM-DD')) }, display: true },
        { title: '维保结束', width: 150, key: 'maintenanceEndTime', render: (h, params) => { return h('span', formatDate(params.row.maintenanceEndTime, 'YYYY-MM-DD')) }, display: true },
        { title: '合同', width: 100, key: 'contractName', display: true },
        { title: '计量单位', width: 100, key: 'measureUnit', display: true },
        { title: '数量', width: 100, key: 'amount', display: true },
        { title: '金额', width: 100, key: 'money', display: true },
        { title: '使用期限', width: 100, key: 'usePeriod', display: true },
        // { title: '使用部门', width: 150, key: 'managementOrgName', display: true },
        // { title: '使用人', width: 100, key: 'managementUserName', display: true },
        { title: '用途', key: 'purpose', display: true },
        { title: '备注', key: 'note', display: true }
      ],
      // 表单验证规则
      rules: {
        title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
        receiveDate: [{ required: true, message: '验收日期不能为空', trigger: 'blur' }],
        categories: [{ required: true, message: '请选择入库类型', trigger: 'blur' }],
        // contractCode: [{ required: true, message: '合同不能为空', trigger: 'change' }],
        // purchaseDate: [{ required: true, message: '购置日期不能为空', trigger: 'blur' }],
        location: [{ required: true, message: '存放位置不能为空', trigger: 'blur' }],
        remark: [
          { max: 500, message: '长度不能超过500', trigger: 'blur' }
        ]
      },
      /** 所有仓库 */
      storehouses: [],
      /** 编辑 */
      selectRow: null,
      /** 资产组件传递参数 */
      editId: -1,
      /** 配件组件传参数 */
      goodsEditId: -1,
      /** 配件编辑 */
      selectGoodsFileRow: null
    }
  },
  computed: {
    myStorehouses: function() {
      const flatTree = this.flattenTreeDataClosure(this.availableLocations)
      return this.storehouses.filter(it => !!flatTree.find(n => n.code === it.locationCode)).map(it => {
        return {
          code: it.locationCode,
          title: it.locationName
        }
      })
    }
  },
  created() {
    this.fetch()
    this.formItem.receiveDate = new Date()
    locationTree('kj').then(response => {
      this.availableLocations = response.data
      this.flattenTreeData = this.flattenTreeDataClosure(this.availableLocations)
    })
    getAllStorehouse().then(response => {
      this.storehouses = response.data
    })
  },
  methods: {
    // 获取借用工单信息
    fetch() {
      if (this.workOrderNum !== 'NULL') {
        detail(this.workOrderNum, this.taskId).then(response => {
          this.formItem = {
            ...response.data
          }
        })
      } else {
        this.formItem = { ...formItem }
      }
      this.changeCol(this.formItem.categories)
    },
    commit(temporary) {
      this.$refs.myform1.validate((valid) => {
        if (valid) {
          if (this.formItem.assetList.length === 0) {
            return this.$message({
              showClose: true,
              message: '没有可入库的资产',
              type: 'error'
            })
          }
          const data = this.formItem
          if (this.orderStatus === 'revoked') {
            data.workOrderNum = null
            data.taskId = null
          } else {
            data.workOrderNum = this.workOrderNum
            data.taskId = this.taskId
          }
          // data.workOrderNum = this.workOrderNum
          // data.taskId = this.taskId
          data.temporary = temporary
          // 时间
          data.receiveDate = new Date(this.formItem.receiveDate).getTime()
          // ge.x 2022-04-08 增加锁屏功能
          const loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          create(data).then(res => {
            if (res.status === 'success') {
              this.formItem.assetList = []
              formItem.assetList = []
              loading.close()
              this.$emit('cancelNewOrderForm', 'refresh')
            }
          }).catch(() => {
            this.formItem.assetList = []
            formItem.assetList = []
            loading.close()
            this.$emit('cancelNewOrderForm', 'refresh')
          })
        }
      })
    },
    btnCancel() {
      this.formItem.assetList = []
      formItem.assetList = []
      this.formItem.goodsFileList = []
      formItem.goodsFileList = []
      this.$emit('cancelNewOrderForm', 'refresh')
    },
    // 位置选择
    selectLocation(obj) {
      this.formItem.locationName = obj.title || ''
    },
    // 位置选择
    inputLocation(value) {
      if (!value) {
        this.formItem.locationName = value || ''
      }
    },
    /** 分类变化 */
    categorieChange(value) {
      // 清空资产信息
      this.formItem.assetList = []
      this.formItem.goodsFileList = []
      this.changeCol(value)
    },
    /** 显示列变化 */
    changeCol(value) {
      let hiddenColumns = []
      if (value === '3') {
        hiddenColumns = ['bigTypeName', 'middleTypeName', 'originalCode', 'supplierName', 'code', 'card', 'serialnumber', 'computerRoom', 'cabinet', 'location', 'maintenanceStartTime', 'maintenanceEndTime', 'contractName', 'usePeriod', 'managementOrgName', 'managementUserName']
      } else {
        hiddenColumns = ['card', 'amount']
      }
      this.insideColumns = this.sInsideColumns.filter(e => !hiddenColumns.includes(e.key))
    },
    // 扁平化树形结构
    flattenTreeDataClosure(data) {
      const treeData = data
      const flattenData = []
      function flattenTree(data, parentKey) {
        data.forEach(ele => {
          const { title, code, children } = ele
          flattenData.push({ title, code, parentKey })
          if (children) {
            flattenTree(children, code)
          }
        })
      }
      flattenTree(treeData, null)
      return flattenData
    },
    /** 编辑数据 */
    editRow(scope) {
      this.selectRow = clone(scope.row)
      this.editId = scope.$index
      this.assetDialogFormVisible = true
    },
    /** 配件编辑数据 */
    editGoodsFileRow(scope) {
      this.selectGoodsFileRow = clone(scope.row)
      this.goodsEditId = scope.$index
      this.goodsFileDialogFormVisible = true
    },
    /** 移除一条数据 */
    remove(row) {
      const i = this.formItem.assetList.lastIndexOf(row)
      this.formItem.assetList.splice(i, 1)
    },
    /** 移除一条数据 */
    removeGoodsFile(row) {
      const i = this.formItem.goodsFileList.lastIndexOf(row)
      this.formItem.goodsFileList.splice(i, 1)
    },
    /** 资产选择 */
    ok() {
      const _this = this
      // 直接调用表单实例的保存方法
      _this.$refs.editForm.save().then(response => {
        if (response === false) return
        if (_this.editId === -1) {
          _this.formItem.assetList.push({ ...response, id: null })
        } else {
          _this.formItem.assetList[this.editId] = { ...clone(response) }
          _this.formItem.assetList.splice(1, 0)
        }
        // 关闭对话框
        _this.assetDialogFormVisible = false
        _this.editId = -1
        _this.selectRow = null
      })
    },
    /** 资产取消 */
    cancel() {
      this.assetDialogFormVisible = false
      this.editId = -1
      this.selectRow = null
    },
    /** 资产选择 */
    goodsFileOk() {
      const _this = this
      // 直接调用表单实例的保存方法
      _this.$refs.goodsEditForm.save().then(response => {
        if (response === false) return
        if (_this.goodsEditId === -1) {
          _this.formItem.goodsFileList.push({ ...response, id: null })
        } else {
          _this.formItem.goodsFileList[this.goodsEditId] = { ...clone(response) }
          _this.formItem.goodsFileList.splice(1, 0)
        }
        // 关闭对话框
        _this.goodsFileDialogFormVisible = false
        _this.goodsEditId = -1
        _this.selectGoodsFileRow = null
      })
    },
    /** 配件弹窗取消 */
    goodsFileCancel() {
      this.goodsFileDialogFormVisible = false
      this.goodsEditId = -1
      this.selectGoodsFileRow = null
    }
  }
}
</script>
<style>
  .el-table th.gutter{
    display: table-cell !important;
  }
</style>
